/**
 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.senyint.imsdk.packet;

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jivesoftware.smack.packet.PacketExtension;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 回复消息发送方已经收到的标识<br>
 * 	返回消息id
 * 此类型仅限于chat
 */
public class DeliveryRecv implements PacketExtension
{
    public static final String NAMESPACE = "urn:syt:recv";
    public static final String ELEMENT = "recv";
    public static final String KEY = "key";
    

    private String id; /// original ID of the delivered message

    public DeliveryRecv(){}
    
    public DeliveryRecv(String id)
    {
        this.id = id;
    }

    public String getId()
    {
        return id;
    }

    @Override
    public String getElementName()
    {
        return ELEMENT;
    }

    @Override
    public String getNamespace()
    {
        return NAMESPACE;
    }

    /**
     * 如果id==null，则意味着这是请求对方回复的一个消息
     */
    @Override
    public String toXML()
    {
    	StringBuffer sb = new StringBuffer();
    	sb.append("<").append(ELEMENT).append( " xmlns='").append(NAMESPACE).append("'>");
    	sb.append("<key>").append(id).append("</key>");
    	sb.append("</").append(ELEMENT).append(">");
    	return sb.toString();
    }
    

    public static DeliveryRecv parse(String xml) {
    	DeliveryRecv dse = new DeliveryRecv();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            int size = nodeList.getLength();
            for (int i = 0; i < size; i++) {
                Node node = nodeList.item(i);
                String nodeName = node.getNodeName();
                if (nodeName.equals(KEY)) {
                	dse.id = node.getTextContent();
                } 
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dse;
    }

    
}
